<?php
require_once ('php-soundcloud/Soundcloud.php');
require_once ('functions.php');

// Create the soundcloud object based on keys/uri specified in keys.php
$soundcloud = new Services_Soundcloud($soundcloudConsumerKey, $soundcloudConsumerSecret, $soundcloudRedirectUri);
$userinfo = $session->userinfo;
$userid = $userinfo['id'];

// Retreive access tokens if missing.
if (isset($_GET['code'])) {
	try {
		$accessToken = $soundcloud->accessToken($_GET['code']);
	} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
		exit($e->getMessage());
	}
	//print_r($accessToken);
	
	// Attempt to store access and refresh tokens in DB
	$success = update_network_token('soundcloud', $userid, $accessToken['access_token'], $accessToken['refresh_token']);
	if($success) {
		header("Location: ".FULL_PATH."index.php?msg=SoundcloudAdded");
		exit; 
		} 
	else {
		header("Location: ".FULL_PATH."index.php?msg=ERROR");
		exit;
	}
} 

$displayOutput = false;
// If user is auth'ed, retrieve information. Otherwise don't display output
if($userkeys = is_integrated_with("soundcloud", $userid)) {
	try {
		$soundcloud->setAccessToken($userkeys['usertoken']);
		$me = json_decode($soundcloud->get('me'), true);
	} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
		$newTokens = $soundcloud->accessTokenRefresh($userkeys['usersecret']);
		update_network_token('soundcloud', $userid, $newTokens['access_token'], $newTokens['refresh_token']);
	}
	
	// Get some embedding code for tracks
	
	$tracks = $soundcloud->get('me/tracks');
	$tracks = json_decode($tracks, true);
	
	$displayOutput = true;
} 
?>
<?php if($displayOutput): ?>
<div class = "box feedbox margin">
	<table>
	<tr>
      <td><a href = "<?=$me['permalink_url']?>"><img src = "layout/soundcloud-icon.gif" height='48px' width='48px'/></a></td>
      <td><a href = "<?=$me['permalink_url']?>"><h3>Soundcloud</h3></a></td>
	</tr>
	<tr> 
	  <td class="title"><img src="<?=$me['avatar_url']?>" /> Tracks from <?=$me['permalink']?></td>
	</tr>
	</table>
	<?php
	  if (isset($tracks)){

		foreach($tracks as $track){
			$permalink_url = $track['permalink_url'];
			$permalink_url = urlencode($permalink_url);
			$fullUrl = 'http://soundcloud.com/oembed?url='. $permalink_url;

			$resp = json_decode($soundcloud->get($fullUrl), true);
			
			echo  $resp['html'] . '<br /><br />';
		}

	  } else {
		 echo "Failed to retrieve songs.";
	  }
	?>
	
	<div class = "clear"></div>
</div>
<?php endif; ?>

      
